package com.wqr.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wqr.exception.MD5Util;
import com.wqr.pojo.LogInfo;
import com.wqr.pojo.Login;
import com.wqr.pojo.UserStates;
import com.wqr.pojo.UserTypes;
import com.wqr.service.LogInfoService;
import com.wqr.service.LoginService;
import com.wqr.service.UserStatesService;
import com.wqr.service.UserTypesService;
@Controller
public class LoginController extends BaseController {
	@Autowired
    public LoginService loginService;
	@Autowired
    public LogInfoService logInfoService;
	@Autowired
	public UserStatesService userStateService;
	@Autowired
	public UserTypesService userTypesService;
	
	@RequestMapping("/registerAdd")
    public String registerAdd(String loginname ,String password , String email, Model model,Login login) throws Exception {
        String msg = null;
        if(loginService.isExistEmail(email)){
            msg = "邮箱已存在，无法注册，请重新输入";
        }
        if(loginService.isExistName(loginname)){
            msg = "用户名已存在，无法注册，请重新输入";
        }
        if (msg != null ) {
        	model.addAttribute("alertMsg", getAlertScript(msg));
            return "register";
        }else {
        	login.setLoginName(loginname);
            login.setPassword(password);
            login.setEmail(email);
            login.setRegisterTime(new Date());
            loginService.add(login);
            return "redirect:/login.action";
        }
    }

    @RequestMapping("/loginIn")
    public String loginIn(String loginname ,String password , Model model, 
    		HttpSession session) throws Exception{
    	String msg = null;
    	//String refer = null;
    	Login login = loginService.get(loginname,password);
        if(login == null){
        	if(!loginService.isExistName(loginname)){
                msg = "该用户名还未注册，请注册";
                model.addAttribute("alertMsg", getAlertScript(msg));
                return "login";
            }
            msg = "用户名密码错误，请重试";
            model.addAttribute("alertMsg", getAlertScript(msg));
            return "login";
        }
        
        session.setAttribute("login",login);
        
        //refer = login.getLoginName();
        //判断userStates和userType
        UserStates userStates = userStateService.selectByPrimaryKey(login.getUserStateId());
        UserTypes userTypes = (UserTypes) userTypesService.selectByPrimaryKey(login.getUserTypeId());
        if(!userStates.getCanlogin()) {
    	   msg = "该用户处于"+ userStates.getUserStateName() +"状态，不可登陆！";
           model.addAttribute("alertMsg", getAlertScript(msg));
           return "login";
        }
        
        //添加登陆日志
        LogInfo logInfo = new LogInfo();
        logInfo.setLoginId(login.getLoginId());
        logInfo.setLoginName(login.getLoginName());
        logInfo.setLoginTime(new Date());
        logInfo.setDescription(login.getRemark());
        logInfoService.insertLogInfo(logInfo);
        
        return "redirect:/"+userTypes.getDefaultPage()+".action";
    }
    @RequestMapping("/logout")
    public String adminLogout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute("login");
        return "redirect:/login.action";
    }
    @RequestMapping("/checkLogin")
    public String checkLogin(Model model,HttpSession session){
        String msg = session.getAttribute("login")!=null?"success":"fail";
        model.addAttribute("alertMsg", getAlertScript(msg));
        return "login";
    }
    
    @RequestMapping("/manageLogin")
	public String login(Model model) throws Exception {
		List<Login> list = loginService.list();
		model.addAttribute("itemList", list);
	    return "manageLogin"; 
	}
    @RequestMapping("/addLogin")
	@ResponseBody// 返回的数据不是html标签的页面，而是其他某种格式的数据时（如json、xml等）使用；
	public int addLogin(@RequestBody //读取Request请求的body部分数据,再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上
			Login login,HttpSession session) throws Exception {
    	login.setRegisterTime(new Date());
    	login.setPassword(MD5Util.md5Encode("123456"));
		int a = loginService.insertLogin(login);
		return a;
	}
	@RequestMapping("/deleteLogin")
	@ResponseBody// 返回的数据不是html标签的页面，而是其他某种格式的数据时（如json、xml等）使用；
	public int deleteLogin(@RequestBody //读取Request请求的body部分数据,再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上
			Login login) throws Exception {
		//@pathVariable //将 URL 中占位符参数绑定到控制器处理方法的入参中 URL 中的 {xxx} 占位符可以通过@PathVariable("xxx") 绑定到操作方法的入参中。
		int a = loginService.delectLogin(login.getLoginId());
		return a;
	}
	@RequestMapping("/updateLogin")
	@ResponseBody
	public Login updateLogin(@RequestBody Login login) throws Exception {
		Login itemList = loginService.selectByPrimaryKey(login);
		return itemList;
	}
	@RequestMapping("/saveLogin")
	@ResponseBody// 返回的数据不是html标签的页面，而是其他某种格式的数据时（如json、xml等）使用；
	public int saveLogin(@RequestBody Login login,HttpSession session) throws Exception {
		int a = loginService.updateLogin(login);
		return a;
	}
	@RequestMapping("/searchLogin")
	@ResponseBody
	public List<Login> searchLogin(@RequestBody Login login) throws Exception {
		if(login.getLoginName() == ""){
			login.setLoginName(null);
		}
		if(login.getEmail() == ""){
			login.setEmail(null);
		}
		
		List<Login> itemList = loginService.selectLoginByDIY(login);
	    return itemList;
	}
	@RequestMapping("/searchAllLogin")
	@ResponseBody
	public List<Login> searchAllLogin() throws Exception {
		List<Login> itemList = loginService.list();
	    return itemList;
	}
}
